﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Configuration.Assemblies;
using Serilog;

using Wpf.Ui.Controls;

using MessageBox = System.Windows.MessageBox;

namespace CokeeAgent.Dashboard
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string serviceFilePath = $"{Environment.CurrentDirectory}\\CokeeAgent.exe";
        private string serviceName = "CokeeAgent";
        public ServiceControllerStatus lastStatus;
        public Timer timer = new Timer(3000);

        public MainWindow()
        {
            InitializeComponent();
            Log.Logger = new LoggerConfiguration()
                          .WriteTo.File("log.txt")
                          .WriteTo.RichTextBox(logBox)
                          .CreateLogger();
            CheckStatus();
            timer.Elapsed += (sender, e) => CheckStatus();
            timer.Start();
        }

        private void Load(object sender, RoutedEventArgs e)
        {
        }

        public void CheckStatus()
        {
            if (IsServiceExisted(serviceName))
            {
                using (ServiceController control = new ServiceController(serviceName))
                {
                    //control.WaitForStatus(ServiceControllerStatus.Running,new TimeSpan(30000000));
                    if (control.Status == ServiceControllerStatus.Running) LogBar(InfoBarSeverity.Success, "Service Running!");
                    else if (control.Status == ServiceControllerStatus.Stopped) LogBar(InfoBarSeverity.Warning, "Service Exist，but stopped。");
                    else
                    {
                        Log.Information($"Service {serviceName} status: {control.Status}");
                        LogBar(InfoBarSeverity.Warning, $"服务存在，但非正常运行。当前状态: {control.Status}");
                    }
                }
            }
            else
            {
                //Log.Error($"Can't find Service {serviceName} in services list.");
                LogBar(InfoBarSeverity.Error, $"服务不存在!");
            }
        }

        //事件：安装服务
        private void Install(object sender, RoutedEventArgs e)
        {
            try
            {
                Task.Run(() =>
                {
                    if (IsServiceExisted(serviceName)) { Log.Error("Already installed."); return; }
                    using (AssemblyInstaller installer = new AssemblyInstaller())
                    {
                        installer.UseNewContext = true;
                        installer.Path = serviceFilePath;
                        IDictionary savedState = new Hashtable();
                        installer.Install(savedState);
                        installer.Commit(savedState);
                    }
                }).ContinueWith(t =>
                {
                    if (IsServiceExisted(serviceName)) Log.Information("Install service successfully.");
                    CheckStatus();
                });
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
            }
        }

        private void Run(object sender, RoutedEventArgs e)
        {
            Log.Information("Try to start service...");
            if (this.IsServiceExisted(serviceName)) this.ServiceStart(serviceName);
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Stopped)
                {
                    control.Start();
                }
            }
            CheckStatus();
        }

        private void Stop(object sender, RoutedEventArgs e)
        {
            if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName);
            Log.Information("Try to stop service...");
            CheckStatus();
        }

        private void Uninstall(object sender, RoutedEventArgs e)
        {
            if (this.IsServiceExisted(serviceName))
            {
                this.ServiceStop(serviceName);
                this.UninstallService(serviceFilePath);
                MessageBox.Show("Done:" + serviceName, serviceFilePath);
            }
        }

        //判断服务是否存在
        private bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController sc in services)
            {
                if (sc.ServiceName.ToLower() == serviceName.ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        //卸载服务
        private void UninstallService(string serviceFilePath)
        {
            try
            {
                Task.Run(() =>
                {
                    using (AssemblyInstaller installer = new AssemblyInstaller())
                    {
                        installer.UseNewContext = true;
                        installer.Path = serviceFilePath;
                        installer.Uninstall(null);
                    }
                }).ContinueWith(t =>
                {
                    if (!IsServiceExisted(serviceName)) Log.Information("Service uninstall successfully.");
                    CheckStatus();
                });
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
            }
        }

        //启动服务
        private void ServiceStart(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Stopped)
                {
                    control.Start();
                }
            }
        }

        //停止服务
        private void ServiceStop(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Running)
                {
                    control.Stop();
                }
            }
        }

        public void LogBar(InfoBarSeverity severity, string str)
        {
            Dispatcher.Invoke(new Action(() =>
            {
                infobar.Severity = severity;
                infobar.Message = str;
            }));
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
        }
    }
}
}